package com.hmkj.admin.controller.order;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmkj.admin.controller.BaseController;
import com.hmkj.admin.controller.GenericController;
import com.hmkj.admin.utils.AdminSessionHelper;
import com.hmkj.common.entity.ResultEntity;
import com.hmkj.common.entity.dtgrid.DtGrid;
import com.hmkj.common.entity.export.ExportUtils;
import com.hmkj.common.utils.DateUtils;
import com.hmkj.common.utils.StringUtils;
import com.hmkj.common.utils.ValidateUtils;
import com.hmkj.core.constant.Enum;
import com.hmkj.core.exception.BussinessException;
import com.hmkj.core.model.investAccountLog.InvestAccountLogModel;
import com.hmkj.core.model.order.OrderModel;
import com.hmkj.core.po.account.AccountLog;
import com.hmkj.core.po.order.Order;
import com.hmkj.core.po.system.Admin;
import com.hmkj.core.po.user.User;
import com.hmkj.core.service.account.AccountLogService;
import com.hmkj.core.service.investAccountLog.InvestAccountLogService;
import com.hmkj.core.service.order.OrderOperationService;
import com.hmkj.core.service.order.OrderService;
import com.hmkj.core.service.user.UserService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

@Controller
@RequestMapping(BaseController.BASE_URI)
public class OrderJsonController extends GenericController<Integer, Order> {

    @Autowired
    private InvestAccountLogService investAccountLogService;
    @Autowired
    private OrderOperationService orderOperationService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;
    @Autowired
    private AccountLogService accountLogService;

    private Order checkPrimaryKey(Integer id) throws Exception {
        if (null == id) {
            throw new BussinessException("参数有误");
        } else {
            Order order = orderService.selectByPrimaryKey(id);
            if (null != order) {
                return order;
            } else {
                throw new BussinessException("参数有误");
            }
        }
    }

    /**
     * 交易记录数据
     */
    @RequestMapping(value = "tradeLog/list.json", method = RequestMethod.POST)
    @ResponseBody
    public DtGrid tradeLogJson(String dtGridPager) throws Exception {
        return investAccountLogService.getDtGridList(dtGridPager, InvestAccountLogModel.class);
    }

    /**
     * 资金记录
     */
    @RequestMapping(value = "moneyDetail/list.json", method = RequestMethod.POST)
    @ResponseBody
    public DtGrid moneyDetailJson(String dtGridPager) throws Exception {
        DtGrid dtGrid = new DtGrid();
        dtGrid = accountLogService.getDtGridList(dtGridPager, AccountLog.class);
        return dtGrid;
    }


    /**
     * 方案列表json数据
     *
     * @param dtGridPager 分页插件
     * @return DtGrid
     */
    @ResponseBody
    @RequestMapping(value = "/order/list.json", method = RequestMethod.POST)
//    @RequiresPermissions("sys:order:list")
    public DtGrid listJson(String dtGridPager) throws Exception {
        DtGrid dtGrid = new DtGrid();
        dtGridPager = dataAuthority(dtGridPager);
        Admin admin = AdminSessionHelper.getCurrAdmin();
        if (admin.getRoleId() == Enum.INVEST_ROLE_ID) {
            ObjectMapper mapper = new ObjectMapper();
            DtGrid dtGrid1 = mapper.readValue(dtGridPager, DtGrid.class);
            if (dtGrid1.getFastQueryParameters().get("eq_status") != null) {
                Integer status = Integer.parseInt(dtGrid1.getFastQueryParameters().get("eq_status").toString());
                if (status != Order.STATUS.T1.code && status != Order.STATUS.T8.code) {
                    Map<String, Object> dtGridFastQueryParameters = dtGrid1.getFastQueryParameters();
                    dtGridFastQueryParameters.put("eq_investor_id", admin.getUserId());
                    dtGrid1.setFastQueryParameters(dtGridFastQueryParameters);
                    dtGridPager = dtGrid1.toJsonString();
                }
            }
        }
        dtGrid = orderService.getDtGridList(dtGridPager, OrderModel.class);
        List<Object> list = dtGrid.getExhibitDatas();
        List<Object> objects = new ArrayList<>();
        //匹配中列表增加邀请人字段
        if (CollectionUtils.isNotEmpty(list)) {
            for (Object obj : list) {
                LinkedHashMap model = (LinkedHashMap) obj;
                Integer state = Integer.parseInt(model.get("status").toString());
                if (state == Order.STATUS.T3.code) {
                    model.put("currentProfit", orderService.getOrderCurrentProfit(Integer.parseInt(model.get("id").toString())));
                } else if (state == Order.STATUS.T1.code) {
                    User user = userService.selectByPrimaryKey(Integer.valueOf(model.get("userId").toString()));
                    if (StringUtils.isNotBlank(user.getInviteId())) {
                        User inviter = userService.selectByPrimaryKey(user.getInviteId());
                        model.put("inviterName", inviter.getUserName());
                    }
                } else if (state == Order.STATUS.T7.code && model.get("profitCount") != null &&
                        Double.parseDouble(model.get("profitCount").toString()) >= 0) {
                    double investProfit = Double.parseDouble(model.get("profitCount").toString()) * (1 - Double.parseDouble(model.get("profitCount").toString()));
                    model.put("investProfit", investProfit);
                }
                objects.add(model);
            }
            dtGrid.setExhibitDatas(objects);
        }
        return dtGrid;
    }

    /**
     * 抢单功能
     */
    @ResponseBody
    @RequestMapping(value = "/order/scramble.json")
    @RequiresPermissions("sys:order:scramble")
    public ResultEntity scrambleOrder(Integer id) throws Exception {
        Admin admin = AdminSessionHelper.getCurrAdmin();
        Order order = checkPrimaryKey(id);
        if (admin.getRoleId() != Enum.UserType.INVESTOR.getValue()) {
            throw new BussinessException("非投资人无法抢单!!");
        }
        orderService.doScrambleOrder(order, admin);
        return ok();
    }

    /**
     * 抢单回填
     */
    @ResponseBody
    @RequestMapping("/order/back.json")
    public ResultEntity robbing(Integer id,Integer buyDealNumber,BigDecimal buyDealPrice) throws Exception {
        //校验是否是投资人流单
        Admin admin = AdminSessionHelper.getCurrAdmin();
        Order order = checkPrimaryKey(id);
        if (admin.getUserId() != order.getInvestorId()) {
            throw new BussinessException("您无权操作此订单");
        }
        if (order.getStatus() != Order.STATUS.T2.code) {
            throw new BussinessException("当前订单状态不能抢单回填或已抢单回填");
        }
        order.setBuyDealNumber(buyDealNumber);
        order.setBuyDealPrice(buyDealPrice);
        orderService.doOrderBack(order, admin);
        return ok();
    }


    /**
     * 流单
     */
    @ResponseBody
    @RequestMapping("/order/flow.json")
    public ResultEntity orderFlow(Integer id) throws Exception {
        //校验是否是投资人流单
        Admin admin = AdminSessionHelper.getCurrAdmin();
        Order order = checkPrimaryKey(id);
        if (admin.getUserId() != order.getInvestorId()) {
            throw new BussinessException("您无权操作此订单");
        }
        if (order.getStatus() != Order.STATUS.T2.code && order.getStatus() != Order.STATUS.T1.code) {
            throw new BussinessException("只有匹配中和交易中的订单才能流单");
        }
        orderService.doFlowOrder(id, admin);
        return ok();
    }

    /**
     * 订单结算
     *
     * @param id id
     * @return ResultEntity
     */
    @ResponseBody
    @RequestMapping(value = "/order/verify.json", method = RequestMethod.POST)
    @RequiresPermissions("sys:account:verify")
    public ResultEntity verifyOrder(Integer id) throws Exception {
        Admin admin = AdminSessionHelper.getCurrAdmin();
        //查询是否是待结算的订单
        Order order = checkPrimaryKey(id);
        if (admin.getUserId() != order.getInvestorId()) {
            throw new BussinessException("您无权操作此订单");
        }
        //计算盈亏，状态改为已结算
        //根据买入成交价格，买入成交数量，卖出成交价格卖出成交数量计算盈亏
        if (!Objects.equals(order.getStatus(), Order.STATUS.T6.code)) {
            throw new BussinessException("订单状态不正确，请刷新");
        }
        orderService.doAccount(order, admin);
        return ok();
    }

    /**
     * 待审核，一键审核通过
     */
    @ResponseBody
    @RequestMapping(value = "/order/oneKeyPass.json", method = RequestMethod.POST)
    @RequiresPermissions("sys:myOrder:waitAcc")
    public ResultEntity onkeyPass(Integer id) throws Exception {
        Admin admin = AdminSessionHelper.getCurrAdmin();
        //查询是否是待结算的订单
        Order order = checkPrimaryKey(id);
        if (admin.getUserId() != order.getInvestorId()) {
            throw new BussinessException("您无权操作此订单");
        }
        if (!Objects.equals(order.getStatus(), Order.STATUS.T6.code)) {
            throw new BussinessException("订单状态不正确，请刷新");
        }
        //结算
        orderService.doAccount(order, admin);
        return ok();
    }

    /**
     * 待平仓-发起平仓指令
     */
    @ResponseBody
    @RequestMapping(value = "/order/goPingcang.json", method = RequestMethod.POST)
    @RequiresPermissions("sys:order:gopingcang")
    public ResultEntity toSell(Integer id) throws Exception {
        Admin admin = AdminSessionHelper.getCurrAdmin();
        Order order = checkPrimaryKey(id);
        if (admin.getUserId() != order.getInvestorId()) {
            throw new BussinessException("您无权操作此订单");
        }
        if (!Objects.equals(order.getStatus(), Order.STATUS.T3.code)) {
            throw new BussinessException("订单状态不正确，请刷新");
        }
        orderService.doSell(order,admin);
        return ok();
    }

    /**
     * 修改持仓中订单信息
     */
    @ResponseBody
    @RequestMapping(value = "/order/doOrderHoldModify.json", method = RequestMethod.POST)
    @RequiresPermissions("sys:orderHold:modify")
    public ResultEntity orderHoldModify(Integer orderId, Integer modifyDealNumber, Double modifyDealPrice) throws Exception {
        Admin admin = AdminSessionHelper.getCurrAdmin();
        if (StringUtils.isBlank(orderId) || StringUtils.isBlank(modifyDealNumber) || StringUtils.isBlank(modifyDealPrice)) {
            throw new BussinessException("参数错误");
        }
        if (!ValidateUtils.isPrice(modifyDealNumber.toString())) {
            throw new BussinessException("股数格式不正确");
        }
        if (modifyDealNumber.toString().length() > 12) {
            throw new BussinessException("股数长度不能超过12位");
        }
        if (!ValidateUtils.isPrice(modifyDealPrice.toString())) {
            throw new BussinessException("买入价格格式不正确");
        }
        if (modifyDealPrice.toString().length() > 11) {
            throw new BussinessException("买入价格长度不能超过11位");
        }
        orderService.modifyHoldingOrder(orderId, modifyDealPrice, modifyDealNumber, admin.getName());
        return ok();
    }

    /**
     * 补亏
     */
    @ResponseBody
    @RequestMapping(value = "/order/repairLoss.json", method = RequestMethod.POST)
    @RequiresPermissions("sys:order:repairLoss")
    public ResultEntity repairLoss(Integer id, BigDecimal repair) throws Exception {
        Admin admin = AdminSessionHelper.getCurrAdmin();
        Order order = checkPrimaryKey(id);
        if (admin.getUserId() != order.getInvestorId()) {
            throw new BussinessException("您无权操作此订单");
        }
        if (!Objects.equals(order.getStatus(), Order.STATUS.T3.code) && !Objects.equals(order.getStatus(), Order.STATUS.T5.code)) {
            throw new BussinessException("订单状态已改变，请刷新");
        }
        orderService.doRepairLoss(order, repair, admin);
        return ok();
    }

    /**
     * 卖出回填
     *
     * @param order order
     * @return ResultEntity
     */
    @ResponseBody
    @RequestMapping(value = "/order/pingcang.json", method = RequestMethod.POST)
    @RequiresPermissions("sys:order:sell")
    public ResultEntity sell(Order order) throws Exception {
        Admin admin = AdminSessionHelper.getCurrAdmin();
        if (StringUtils.isBlank(order.getSellDealNumber().toString())) {
            throw new BussinessException("请输入点卖数量");
        } else if (order.getSellDealNumber().toString().length() > 15) {
            throw new BussinessException("点卖数量长度不能超过15位");
        } else if (!ValidateUtils.isNumber(order.getSellDealNumber().toString())) {
            throw new BussinessException("点卖数量格式不正确");
        } else if (StringUtils.isBlank(order.getSellDealPrice().toString())) {
            throw new BussinessException("请输入点卖价格");
        } else if (order.getSellDealPrice().toString().length() > 15) {
            throw new BussinessException("点卖价格长度不能超过15位");
        } else if (!ValidateUtils.isPrice2(order.getSellDealPrice().toString())) {
            throw new BussinessException("点卖价格格式不正确");
        }
        orderService.doSaleBack(order,admin);
        return ok();
    }

    /**
     * 平仓中撤回
     */
    @ResponseBody
    @RequestMapping(value = "/order/back/Pingcang.json", method = RequestMethod.POST)
    @RequiresPermissions("sys:order:back")
    public ResultEntity orderBack(Integer id) throws Exception {
        Admin admin = AdminSessionHelper.getCurrAdmin();
        Order order = checkPrimaryKey(id);
        if (admin.getUserId() != order.getInvestorId()) {
            throw new BussinessException("您无权操作此订单");
        }
        if (order.getStatus() != Order.STATUS.T5.code) {
            throw new BussinessException("订单已更新，请刷新");
        }
        orderService.doBackWithCoving(order,admin);
        return ok();
    }

    /**
     * 平仓中的数量
     *
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/admin/orderNotify.json", method = RequestMethod.POST)
    public ResultEntity orderNotify() throws Exception {
        Admin currAdmin = AdminSessionHelper.getCurrAdmin();
        Integer notifySize = 0;
        //当前用户平仓中订单数量
        long totalClosingCount = orderService.getTotalClosingCount(currAdmin);
        if (totalClosingCount > 0) {
            notifySize++;
        }
        Integer finalSize = notifySize;
        return ok(m->{
            m.put("totalClosingCount", totalClosingCount);
            m.put("size", finalSize);
        });
    }

    /**
     * 列表导出
     *
     * @param dtGridPager
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "order/listExport.json", method = RequestMethod.POST)
    public ResultEntity export(String dtGridPager, HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 执行导出
        ExportUtils.export(request, response, orderService.getDtGridListExport(dtGridPager, OrderModel.class));
        return ok();
    }


}
